import { ref } from 'vue'
import { ClassTags } from '#/index'
import { defineStore } from 'pinia'
import { useRouter, type RouteLocationNormalizedLoaded } from 'vue-router'

export const useTagsStore = defineStore('tagsStore', () => {
    const router = useRouter()
    const tagList = ref([new ClassTags("/index/dashboard","dashboard","首页")])

    /**
     * 添加路由标签
     * @param route 路由对象
     * @param index 要添加的位置，默认是在末尾
     * @returns 
     */
    function pushTag(route:RouteLocationNormalizedLoaded,index:number = -1){
        const {fullPath,meta,name} = route

        //过滤掉重定向页面
        if('redirectPage' === name) return
        let findTag = tagList.value.find(item=>item.path === fullPath)
        if(!findTag){
            let i = index > -1?index:tagList.value.length
            tagList.value.splice(i,0,new ClassTags(fullPath,name as string,meta.title as string))
        }
    }
    /**
     * 删除tag标签
     * @param index 需要删除的下标
     */
    function removeTag(index:number){
        let route = router.currentRoute.value
        if(route.path == tagList.value[index].path){
            const { path } = (tagList.value[index+1] || tagList.value[index-1])
            router.push(path)
        }
        tagList.value.splice(index,1)
    }
    /**
     * 关闭右侧标签
     * @param path 路由路径
     */
    function closeRightTags(path:string){
        let tempIndex = tagList.value.findIndex(item => item.path === path)
        if (tempIndex > -1) {
            tagList.value.splice(tempIndex + 1)
            sessionStorage.setItem('tagList', JSON.stringify(tagList.value))
            router.push(tagList.value[tempIndex].path)
        }
    }
    /**
     * 关闭所有标签
     */
    function closeAllTags(){
        tagList.value.splice(1)
    }
    function removeTagByPath(fullPath:string){
        let index = tagList.value.findIndex(item=>item.path === fullPath)
            if(-1 != index){
                removeTag(index)
            }
    }
  return {tagList,pushTag,removeTag,closeRightTags,closeAllTags,removeTagByPath}
}, {
    //对个人信息持久化
    persist: {
        key: "tagList",
        storage: window.sessionStorage,
        paths: ["tagList"],
    },
})
